import { HttpException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createTransport, Transporter } from 'nodemailer';
import { CreateEmailDto } from './dto/create-email.dto';
import { RedisService } from 'src/redis/redis.service';
import { EntityManager } from 'typeorm';
import { User } from 'src/user/entities/user.entity';

@Injectable()
export class EmailService {
  private transporter: Transporter;

  constructor(
    private readonly configService: ConfigService,
    private readonly redisService: RedisService,
    private readonly entityManager: EntityManager,
  ) {
    this.transporter = createTransport({
      host: 'smtp.qq.com',
      port: 587,
      secure: false,
      auth: {
        user: this.configService.get('email_username'),
        pass: this.configService.get('email_password'),
      },
    });
  }

  async sendEmail({ to, subject, html }) {
    await this.transporter.sendMail({
      from: {
        name: '系统邮件',
        address: this.configService.get('email_username'),
      },
      to,
      subject,
      html,
    });
  }

  async findUserByEmail(email: string) {
    const user = await this.entityManager.findOne(User, {
      where: { email },
    });
    if (user) {
      return user;
    } else {
      throw new HttpException('用户不存在', 400);
    }
  }

  async login(loginForm: CreateEmailDto) {
    const { email, checkCode } = loginForm;
    const code = await this.redisService.get(email);
    if (!code) throw new HttpException('验证码已过期', 400);

    if (code == checkCode) {
      const user = await this.findUserByEmail(email);
      return user;
    } else {
      throw new HttpException('验证码错误', 400);
    }
  }
}
